package com.smart.home.multi;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 模拟服务器1 handler
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-22
 */
public class Server2Handler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String content = msg.toString(CharsetUtil.UTF_8);
        System.out.println("【服务端】server2接收到信息：" + content);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("【服务端】server2完成读操作，channel ID：" + ctx.pipeline().channel().id());
        for (int i = 0; i < 1000; i++) {
            ctx.writeAndFlush(Unpooled.copiedBuffer(("服务端2第"+i+"发送信息").getBytes(CharsetUtil.UTF_8)));
            Thread.sleep(500);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端server2发生异常");
        cause.printStackTrace();
        ctx.close();
    }
}
